package com.hyy.springbootblog.common.advice;

import com.hyy.springbootblog.common.exception.BlogException;
import com.hyy.springbootblog.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.resource.NoResourceFoundException;


//统一异常处理
@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    @ExceptionHandler(value = Exception.class)//加了value根据value进行捕获
    public Result handler(Exception e) {
        log.error("发生异常：{}",e.getMessage());
        return Result.fail("发生错误",e.getMessage());
    }


    @ExceptionHandler(value = BlogException.class)//加了value根据value进行捕获
    public Result BlogExceptionHandler(Exception e) {
        log.error("发生异常：{}",e.getMessage());
        return Result.fail("发生错误",e.getMessage());
    }


    @ResponseStatus(HttpStatus.NOT_FOUND)//来源于spring framework
    @ExceptionHandler(value = NoResourceFoundException.class)//加了value根据value进行捕获 也来源于spring framework
    public Result NoResourceFoundExceptionHandler(NoResourceFoundException e) {
        log.error("文件不存在：{}",e.getResourcePath());
        return Result.fail("文件不存在："+e.getResourcePath());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = HandlerMethodValidationException.class)//加了value根据value进行捕获
    public Result HandlerMethodValidationExceptionHander(HandlerMethodValidationException e) {
        log.error("参数不合法：{}",e);
        return Result.fail("参数不合法："+e);
    }
}
